const Visitor = require('../db').Visitor

module.exports = {
    async count(ctx, next){
        try {
            const res = await Visitor.findOne({});
            if (res) {
                const saveCount = await Visitor.findOneAndUpdate({},{count:res.count+1})
                if (saveCount._id != null) {
                    ctx.body = {
                        code: 200,
                        msg: `已有${saveCount.count}访问`,
                        count: saveCount.count,
                    }
                } else {
                    ctx.body = {
                        code: 500,
                        msg: `服务器出错`
                    }
                }
            } else {
                const count = new Visitor({ count:1 });
                const saveCount = await count.save();
                if (saveCount._id != null) {
                    ctx.body = {
                        code: 200,
                        msg: `已有${saveCount.count}访问`,
                        count: saveCount.count,
                    }
                } else {
                    ctx.body = {
                        code: 500,
                        msg: `服务器出错`
                    }
                }
            }
        }catch(e){
            ctx.body = '失败诶'
        }
        await next()
    }
}